<template>
	<view>
		<view class="uni-header">
			<uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
			<view class="uni-group">
				<button class="uni-button" v-show="jindu != ''" type="primary" size="mini">{{jindu}}</button>
				<button class="uni-button" type="warn" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">{{ $t('common.button.batchDelete') }}</button>
				<button class="uni-button" type="primary" size="mini" @click="openProductSelector">选择货品</button>
				<input class="uni-search" type="text" v-model="query" @confirm="search"
					:placeholder="$t('common.placeholder.query')" />
				<button class="uni-button hide-on-phone" type="default" size="mini"
					@click="search">{{ $t('common.button.search') }}</button>
				<button class="uni-button" type="primary" @click="chooseFile" size="mini">导入</button>
				<!-- 导入文件 -->
				<!-- <button class="uni-button" type="primary" @click="chooseFile" size="mini">导入</button> -->
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">{{$t('common.button.exportExcel')}}</button>
				</download-excel>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :options="options" :where="where" page-data="replace"
				:orderby="dbOrderBy" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{ data, pagination, loading, error, options }" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange" style="max-height: 710px;">
					<uni-tr>
						<uni-th align="center" width="50">序号</uni-th>
						<uni-th align="center" width="150">货品编码</uni-th>
						<!-- <uni-th align="center" width="100">供应商</uni-th> -->
						<uni-th align="center" width="220">货品名称</uni-th>
						<uni-th align="center" width="180">规格型号</uni-th>
						<uni-th align="center" width="80">计量单位</uni-th>
						<uni-th align="center" width="220">产品中文描述</uni-th>
						<uni-th align="center" width="150">供应商</uni-th>
						<uni-th align="center" width="100">订购数量</uni-th>
						<uni-th align="center" width="120">订购日期</uni-th>
						<uni-th align="center" width="120">预计发货日期</uni-th>
						<uni-th align="center" width="140">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in data" :key="index">
						<uni-td align="center">{{ index + 1 }}</uni-td>
						<uni-td align="center">{{ item.goods_sn }}</uni-td>
						<uni-td align="center">{{ item.name }}</uni-td>
						<uni-td align="center">{{ item.type }}</uni-td>
						<uni-td align="center">{{ item.danwei }}</uni-td>
						<uni-td align="center">{{ item.goods_desc }}</uni-td>
						<uni-td align="center">{{ item.unit_id[0].name }}</uni-td>
						<uni-td align="center">{{ item.order_number || 0 }}</uni-td>
						<uni-td align="center">{{ $formatDate(item.goods_date) }}</uni-td>
						<uni-td align="center">{{ $formatDate(item.yj_goods_date) }}</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<text class="blue cu_po" style="margin-left: 10px;"
									@click="navigateTo('./edit?id=' + item._id, false)">修改</text>
								<text class="red cu_po" style="margin-left: 10px;"
									@click="confirmDelete(item._id)">删除</text>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>

		</view>
		<!-- 选择货品弹窗 -->
		<uni-popup ref="popup" type="dialog" :mask-click="false">
			<view class="popup-content">
				<!-- 搜索框 -->
				<uni-easyinput placeholder="搜索货品" style="width: 300px;" v-model="searchQuery"
					@input="filterProducts"></uni-easyinput>
				<!-- 货品列表 -->
				<view class="popup-content-b" v-show="searchQuery">
					<view class="popup-content-list" v-for="(product, index) in filteredProducts" :key="index"
						@click="selectProduct(product)">
						<text>{{ product.goods_sn }}</text>
						<text style="margin-left: 10px; color: red;">{{ product.remain_count }}</text>
					</view>

				</view>

				<view class="order-info">
					<view class="order-list">
						<uni-forms-item name="goods_sn" :label-width="80" label="货品编码">
							<uni-easyinput placeholder="货品编码" v-model="formData.goods_sn" trim="both"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="name" :label-width="80" label="货品名称">
							<uni-easyinput placeholder="货品名称" v-model="formData.name" trim="both"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="type" :label-width="80" label="规格型号">
							<uni-easyinput placeholder="规格型号" v-model="formData.type" trim="both"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="danwei" :label-width="80" label="计量单位">
							<uni-easyinput placeholder="计量单位" v-model="formData.danwei" trim="both"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="keywords" :label-width="80" label="关键字">
							<uni-easyinput placeholder="商品关键字，为搜索引擎收录使用" v-model="formData.keywords"
								trim="both"></uni-easyinput>
						</uni-forms-item>
					</view>
					<view class="order-list">
						<uni-forms-item required name="unit_id" :label-width="80" label="进货单位">
							<uni-data-select collection="unit" field="_id as value, name as text"
								v-model="formData.unit_id" :localdata="range"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item required name="order_number" :label-width="80" label="订购数量">
							<uni-easyinput placeholder="订购数量" type="number"
								v-model="formData.order_number"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item required name="goods_date" :label-width="80" label="订货日期">
							<uni-datetime-picker return-type="timestamp"
								v-model="formData.goods_date"></uni-datetime-picker>
						</uni-forms-item>
						<uni-forms-item required name="yj_goods_date" :label-width="80" label="预计发货日期">
							<uni-datetime-picker return-type="timestamp"
								v-model="formData.yj_goods_date"></uni-datetime-picker>
						</uni-forms-item>

						<uni-forms-item name="goods_desc" :label-width="80" label="产品中文描述">
							<uni-easyinput placeholder="产品中文描述" v-model="formData.goods_desc"
								trim="both"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="seller_note" :label-width="80" label="">
							<uni-easyinput placeholder="商家备注，仅商家可见" v-model="formData.seller_note"
								trim="both"></uni-easyinput>
						</uni-forms-item>

					</view>
				</view>
				<view class="uni-button-group">
					<button style="margin-right: 30px;" type="primary" class="uni-button" @click="submit">提交</button>
					<button class="uni-button" @click="close" type="default">关闭</button>
				</view>
				<view class="t-c mar-t-15 ">

				</view>
			</view>

		</uni-popup>
	</view>
</template>

<script>
	import * as XLSX from 'xlsx'
	//库存列表
	const db = uniCloud.database();
	const dbCollectionName = 'order-goods';

	// 表查询配置
	const dbOrderBy = 'add_date desc'; // 排序字段
	const dbSearchFields = ['goods_sn', 'keywords', 'name', 'goods_desc']; // 支持模糊搜索的字段列表
	// 分页配置
	const pageCurrent = 1;

	export default {
		data() {
			return {
				time: null,
				requiredFields: {
					unit_id: false,
					order_number: false,
					goods_date: false,
					yj_goods_date: false
				},
				formData: {
					name: "",
					goods_sn: "",
					goods_desc: "",
					danwei: "",
					keywords: "",
					type: "",
					order_number: 0,
					unit_id: null,
					goods_date: null,
					yj_goods_date: null

				},
				jindu: '',
				collectionList: [db.collection('order-goods').getTemp(),
					db.collection('unit').field('name,_id').getTemp()
				],
				selectedIndexs: [],
				query: '',
				where: '',
				dbOrderBy: dbOrderBy,
				exportExcelData: [],
				searchQuery: '', // 搜索框输入内容
				selectedCategory: 0, // 当前选择的类别
				categories: ['全部', '类别1', '类别2'], // 货品类别
				products: [],
				filteredProducts: [], // 筛选后的货品列表
				paginatedProducts: [], // 分页后的货品列表
				currentPage: 1, // 当前页码
				itemsPerPage: 10, // 每页显示数量
				hasMore: true,
				formOptions: {},
				exportExcel: {
					"filename": "订货列表.xls",
					"type": "xls",
					"fields": {
						"货品编码": "goods_sn",
						"货品名称": "name",
						"规格型号": "type",
						"计量单位": "danwei",
						"供应商": "gys",
						"产品中文描述": "goods_desc",
						"订购数量": "order_number",
						"订货日期": "goods_date",
						"预计发货日期": "yj_goods_date",

					}
				},
				options: {
					pageSize: 10,
					pageCurrent
				},
				range: [],
				formData: {},
				columns: [{
						label: 'Name',
						key: 'name'
					},
					{
						label: 'Age',
						key: 'age'
					},
					{
						label: 'Gender',
						key: 'gender'
					}
				],
				tableData: [] // 存储导入的数据
			};
		},
		onLoad() {
			this.getInventory()
		},
		methods: {
			//判断必填 货品提交
			submit() {
				for (let field in this.requiredFields) {
					if (!this.formData[field]) {
						this.requiredFields[field] = true; // 标记为必填
					} else {
						this.requiredFields[field] = false; // 字段有值时移除必填标记
					}
				}

				// 可以在这里添加一个检查机制来判断表单是否填写完整
				const incompleteFields = Object.keys(this.requiredFields).filter(field => this.requiredFields[field]);
				if (incompleteFields.length > 0) {
					uni.showToast({
						icon: 'none',
						title: '必填项为空，请检查:'
					})
				} else {
					this.formData.order_number = this.formData.order_number * 1
					console.log(this.formData);
					db.collection(dbCollectionName)
						.add(this.formData)
						.then(res => {
							uni.showToast({
								title: '新增成功'
							});
							this.formData = {
								name: "",
								goods_sn: "",
								goods_desc: "",
								danwei: "",
								keywords: "",
								type: "",
								order_number: 0,
								unit_id: null,
								goods_date: null,
								yj_goods_date: null

							}
							this.loadData();

						})
						.catch(err => {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							});
						})
						.finally(() => {
							uni.hideLoading();
						});
				}
			},
			//获取库存商品
			async getInventory() {
				let products = []
				let offset = 0
				const batchSize = 500

				while (true) {
					const result = await db.collection('opendb-mall-goods')
						.orderBy('add_date', 'desc')
						.skip(offset)
						.limit(batchSize)
						.get()
					// console.log(res);
					const res = result.result
					if (!res.data.length) break

					products = products.concat(res.data)
					offset += batchSize
				}
				this.products = products
			},
			openProductSelector() {

				this.isProductPopupVisible = true;
				this.filterProducts(); // 初始化筛选
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('center')
			},
			filterProducts() {
				let products = [];
				// 先根据搜索框过滤
				if (this.searchQuery) {
					products = this.products.filter(product => product.goods_sn
						.includes(this.searchQuery));
				}

				// 然后根据选择的类别进行过滤
				if (this.selectedCategory > 0) {
					products = this.products.filter(product => product.category === this.categories[this
						.selectedCategory]);
				}

				this.filteredProducts = products;
				this.paginateProducts(); // 分页
			},
			filterByCategory() {
				this.filterProducts(); // 筛选时按类别过滤
			},
			paginateProducts() {
				const start = (this.currentPage - 1) * this.itemsPerPage;
				const end = this.currentPage * this.itemsPerPage;
				this.paginatedProducts = this.filteredProducts.slice(start, end);
				this.hasMore = this.filteredProducts.length > end; // 判断是否还有更多数据
			},
			loadMore() {
				this.currentPage += 1;
				this.paginateProducts(); // 加载更多
			},
			//添加数据
			selectProduct(product) {
				this.formData = {
					name: "",
					keywords: "",
					goods_sn: "",
					goods_desc: "",
					danwei: "",
					type: "",
					order_number: 0,
					unit_id: null,
					goods_date: null,
					yj_goods_date: null

				}
				this.formData.name = product.name;
				this.formData.goods_sn = product.goods_sn;
				this.formData.goods_desc = product.goods_desc
				this.formData.danwei = product.danwei;
				this.formData.type = product.type;
				this.formData.keywords = product.keywords;
				this.searchQuery = ''
			},
			dateTime(timestamp) {
				console.log();
				const date = new Date(timestamp); // 创建一个 Date 对象
				return date.toLocaleString(); // 转换为本地日期时间字符串
			},
			onqueryload(data) {
				data.forEach(item => {
					item.add_date = this.dateTime(item.add_date)
				})
				this.exportExcelData = data
				// console.log(data);
				// 转换时间戳为北京时间
				const convertToBeijingTime = (timestamp) => {
					const date = new Date(timestamp);
					return date.toLocaleString("zh-CN", {
						timeZone: "Asia/Shanghai"
					});
				};
				this.exportExcelData.map(item => {
					item.gys = item.unit_id[0].name
					item.goods_date = convertToBeijingTime(item.goods_date)
					item.yj_goods_date = convertToBeijingTime(item.yj_goods_date)
				})
			},
			close() {
				this.searchQuery = ''
				this.formData = {
					name: "",
					keywords: "",
					goods_sn: "",
					goods_desc: "",
					danwei: "",
					type: "",
					order_number: 0,
					unit_id: null,
					goods_date: null,
					yj_goods_date: null

				}
				this.$refs.popup.close()
			},
			open(e) {
				this.formData = {
					name: "",
					keywords: "",
					goods_sn: "",
					goods_desc: "",
					danwei: "",
					type: "",
					order_number: 0,
					unit_id: null,
					goods_date: null,
					yj_goods_date: null

				}
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('center')
			},
			getWhere() {
				const query = this.query.trim();
				if (!query) {
					return '';
				}
				let queryRe;
				try {
					queryRe = new RegExp(query, 'i');
				} catch (err) {
					uni.showToast({
						title: '请勿输入\等不满足正则格式的符号',
						icon: 'none'
					});
					return;
				}
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ');
			},
			search() {
				const newWhere = this.getWhere();
				const isSameWhere = newWhere === this.where;
				this.where = newWhere;
				if (isSameWhere) {
					// 相同条件时，手动强制刷新
					this.loadData();
				}
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				});
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0;
				this.$refs.table.clearSelection();
				this.$refs.udb.loadData({
					current: e.current
				});
			},
			navigateTo(url) {
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList;
				console.log(dataList);
				return this.selectedIndexs.map(i => dataList[i]._id);
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: res => {
						this.$refs.table.clearSelection();
					}
				});
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index;
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: res => {
						this.$refs.table.clearSelection();
					}
				});
			},
			//导入
			chooseFile() {
				// 调用文件选择器
				uni.chooseFile({
					extension: ['.xlsx', '.xls'],
					success: (res) => {
						const file = res.tempFiles[0];
						console.log(res, 111);
						this.readExcel(file);
					}
				});
			},
			timeCz(excelDate) {
				console.log(excelDate);
				const timestamp = (excelDate - 25569) * 86400 * 1000 - 28843000; // 25569 是 Excel 日期基准，86400 是一天的秒数
				const date = new Date(timestamp); // 转换为 JavaScript 日期对象
				return new Date(date).getTime()

			},
			sjc(excelTimestamp) {
				// Excel 日期系统是从 1900 年 1 月 1 日开始的
				// 但 JS 的 Date 对象是从 1970 年 1 月 1 日开始的，因此需要做日期偏移。

				// 1900年1月1日到1970年1月1日之间的天数差
				let excelEpochOffset = 25569; // 这个值代表了 1900年1月1日到1970年1月1日的天数差

				// 转换为毫秒
				let millisecondsInDay = 24 * 60 * 60 * 1000;
				let jsTimestamp = (excelTimestamp - excelEpochOffset) * millisecondsInDay;
				// 创建 Date 对象
				let date = new Date(jsTimestamp);

				// 格式化为 "YYYY/MM/DD HH:MM:SS" 格式
				let formattedDate = date.toISOString().replace('T', ' ').split('.')[0];
				let dates = new Date(formattedDate);
				return dates.getTime()
			},
			//处理导入数据
			async readExcel(file) {
				const result = await db.collection('unit').field("_id,name").get()
				const res = result.result
				this.unitList = res.data
				const reader = new FileReader();
				reader.onload = (e) => {
					const binaryString = e.target.result;
					const wb = XLSX.read(binaryString, {
						type: 'binary'
					});
					const ws = wb.Sheets[wb.SheetNames[0]];
					const data = XLSX.utils.sheet_to_json(ws);

					// 处理并存储数据
					this.tableData = data.map(item => ({
						goods_sn: item['货品编码'],
						name: item['货品名称'],
						type: item['规格型号'],
						danwei: item['计量单位'],
						goods_desc: item['产品中文描述'],
						unit_id: item['供应商'],
						order_number: item['订购数量'],
						goods_date: this.sjc(item['订货日期']),
						yj_goods_date: this.sjc(item['预计发货日期']),
					}));
					this.tableData.forEach(item => {
						this.unitList.forEach(iss => {
							if (item.unit_id == iss.name) {
								item.unit_id = iss._id
							}
						})
					})
					console.log(this.tableData, 988);
					// this.tableData = this.tableData.slice(1)
					uni.showLoading({
						title: "导入中" + this.jindu
					});
					// 定义一个函数，接收一个批次的数据，并执行插入操作
					const insertBatch = (batch) => {
						const promises = batch.map(item => {
							return db.collection(dbCollectionName).add({
								danwei: item.danwei,
								goods_sn: String(item.goods_sn),
								goods_desc: String(item.goods_desc),
								name: String(item.name),
								order_number: item.order_number,
								type: String(item.type),
								goods_date: item.goods_date,
								unit_id: item.unit_id,
								yj_goods_date: item.yj_goods_date
							}).catch(error => {
								console.error("Database insert failed:", error);
								return Promise.reject(error);
							});
						});

						return Promise.all(promises);
					};

					// 将所有数据分批处理，每批次大小根据需要调整
					const batchSize = 10; // 每批请求大小
					const batches = [];
					for (let i = 0; i < this.tableData.length; i += batchSize) {
						batches.push(this.tableData.slice(i, i + batchSize));
					}

					// 逐批请求
					let currentBatchIndex = 0;
					const processBatches = async () => {
						const totalBatches = batches.length; // 获取总批次数量
						try {
							for (let i = currentBatchIndex; i < batches.length; i++) {
								await insertBatch(batches[i]); // 等待当前批次处理完成
								this.jindu = `${i + 1}/${totalBatches}`
								currentBatchIndex = i + 1; // 更新当前批次索引
							}
							uni.showToast({
								title: '新增成功',
							});
							setTimeout(() => uni.navigateBack(), 500);
							this.getOpenerEventChannel().emit('refreshData');
						} catch (err) {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							});
						} finally {
							uni.hideLoading();
						}
					};

					// 开始处理批次
					processBatches();

				};

				reader.readAsBinaryString(file);
			},
		}
	};
</script>
<style>
	.uni-table-tr {

		& th:last-child,
		& td:last-child {
			background-color: white;
		}
	}

	.popup-all {
		padding: 15px
	}

	.popup-content {
		background-color: #fff;
		width: 660px;
		height: auto;
		padding: 15px;
	}

	.popup-content-b {
		height: 150px;
		overflow: auto;
		overflow-x: hidden;
	}

	.popup-content-list {
		border-top: 1px solid #ddd;
		/* 边框颜色为浅灰色 */
		padding: 8px 18px;
		/* 稍微增加内边距 */
		cursor: pointer;
		display: flex;
		justify-content: space-between;
		align-items: center;
		/* 保证文字在垂直方向居中 */
		transition: all 0.3s ease;
		/* 添加过渡效果，使hover时变得更平滑 */
		border-radius: 8px;
		/* 圆角效果 */
		background-color: #f9f9f9;
		/* 初始背景色为浅灰色 */
		margin-bottom: 2px;
	}

	.popup-content-list:hover {
		opacity: 0.8;
		/* 提高透明度，增加悬停的立体感 */
		background-color: #f1f1f1;
		/* 浅灰色背景色 */
		color: #333;
		/* 悬停时文本颜色变为深灰色 */
		border-top: 1px solid #aaa;
		/* 增加更明显的边框颜色 */
		box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
		/* 添加阴影效果，使元素浮动 */
		transform: scale(1.02);
		/* 鼠标悬停时微微放大，增加交互感 */
	}

	.order-info {
		display: flex;
		justify-content: space-between;
		padding: 15px;
	}

	.order-list {}
</style>